﻿using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

namespace BLL.Services.AutoCompleteService
{
    public class AutoCompleteCollection
    {
        private readonly string _connectionString;

        public AutoCompleteCollection(string connectionString)
        {
            _connectionString = connectionString;
        }

        private IEnumerable<AutoCompleteItem> GetAutoCompleteResult(string searchPattern, string procedureName)
        {
            var result = new List<AutoCompleteItem>();
            using (var conn = new SqlConnection(_connectionString))
            {
                conn.Open();
                var cmd = new SqlCommand(procedureName, conn) { CommandType = CommandType.StoredProcedure };
                var searchPatternParam = new SqlParameter("@searchPattern", SqlDbType.NVarChar)
                {
                    Value = searchPattern,
                    IsNullable = true
                };
                cmd.Parameters.Add(searchPatternParam);
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var item = new AutoCompleteItem(reader);
                        result.Add(item);
                    }
                }
            }
            return result;
        }

        public IEnumerable<AutoCompleteItem> GetAuthors(string searchPattern)
        {
            return GetAutoCompleteResult(searchPattern, StoredProcedures.ProcedureNames.AutoComplete.GetAuthors);
        }

        public IEnumerable<AutoCompleteItem> GetCategories(string searchPattern)
        {
            return GetAutoCompleteResult(searchPattern, StoredProcedures.ProcedureNames.AutoComplete.GetCategories);
        }

        public IEnumerable<AutoCompleteItem> GetUsersEmails(string searchPattern)
        {
            return GetAutoCompleteResult(searchPattern, StoredProcedures.ProcedureNames.AutoComplete.GetUsersEmails);
        }

        public IEnumerable<AutoCompleteItem> GetBooks(string searchPattern)
        {
            return GetAutoCompleteResult(searchPattern, StoredProcedures.ProcedureNames.AutoComplete.GetBooks);
        }
    }
}